// pages/userInfo/message/message.js
const app = getApp()
import api from '../../../config/api'
import path from '../../../config/path'
const { $Toast } = require('../../../dist/base/index');
const bubbleMixin = require('../../../utils/page-mixin');

Page({
  ...bubbleMixin,
  data: {
    messageList: [],
    loading: false,
    pageNo: 1,
    pageSize: 10,
    finished: false,
    currentUserId: null,
    picLocal: app.globalData.picLocal
  },

  onLoad() {
    console.log('消息页面加载')
    const userInfo = wx.getStorageSync('userInfo') || {}
    this.setData({
      currentUserId: userInfo.id || null
    })
    this.loadMessages(true)
  },

  onShow() {
    console.log('消息页面显示')
    this.loadMessages(true)
  },

  loadMessages(reset = false) {
    if (reset) {
      this.setData({
        pageNo: 1,
        finished: false,
        messageList: []
      })
    }
    if (this.data.loading || this.data.finished) {
      return
    }

    this.setData({ loading: true })
    const params = {
      pageNo: this.data.pageNo,
      pageSize: this.data.pageSize
    }

    console.log('开始加载消息列表，参数:', params)

    api.get('message',path.path.getMessageList, params).then(res => {
      console.log('消息列表接口返回:', res)
      const page = res.data || {}
      const list = page.records || page.list || []
      const total = page.total || page.count || list.length
      const merged = (reset ? [] : this.data.messageList).concat(
        list.map(item => ({
          ...item,
          displayTime: this.formatTime(item.lastTime),
          preview: item.lastMessage || '暂无内容'
        }))
      )
      const hasMore = merged.length < total
      this.setData({
        messageList: merged,
        pageNo: hasMore ? this.data.pageNo + 1 : this.data.pageNo,
        finished: !hasMore
      })
      console.log('消息列表加载完成，数量:', merged.length)
    }).catch(err => {
      console.error('加载消息失败:', err)
      $Toast({
        content: '消息加载失败，请稍后重试',
        icon: 'warning_fill'
      })
    }).finally(() => {
      this.setData({ loading: false })
      wx.stopPullDownRefresh()
    })
  },

  // 修改为跳转到聊天页面
  openConversation(e) {
    console.log('点击消息项，事件对象:', e)
    const { userid, username, avatar } = e.currentTarget.dataset
    console.log('提取的参数:', { userid, username, avatar })
    
    if (!userid) {
      console.log('userid为空，无法跳转')
      $Toast({
        content: '无法打开对话',
        icon: 'warning_fill'
      })
      return
    }
    
    console.log('准备跳转到聊天页面')
    
    // 跳转到聊天页面
    wx.navigateTo({
      url: `/pages/userInfo/chatmessage/chatmessage?userId=${userid}&userName=${username || '用户'}&avatar=${avatar || ''}`,
      success: () => {
        console.log('跳转成功')
      },
      fail: (err) => {
        console.error('跳转失败:', err)
        $Toast({
          content: '跳转失败',
          icon: 'warning_fill'
        })
      }
    })
  },

  formatTime(timeStr) {
    if (!timeStr) {
      return ''
    }
    const date = new Date(timeStr)
    if (Number.isNaN(date.getTime())) {
      return timeStr
    }
    const now = new Date()
    const diff = now.getTime() - date.getTime()
    
    // 如果是今天，显示时间
    if (date.toDateString() === now.toDateString()) {
      const hh = `${date.getHours()}`.padStart(2, '0')
      const mm = `${date.getMinutes()}`.padStart(2, '0')
      return `${hh}:${mm}`
    }
    
    // 如果是昨天
    const yesterday = new Date(now)
    yesterday.setDate(yesterday.getDate() - 1)
    if (date.toDateString() === yesterday.toDateString()) {
      return '昨天'
    }
    
    // 其他情况显示日期
    const y = date.getFullYear()
    const m = `${date.getMonth() + 1}`.padStart(2, '0')
    const d = `${date.getDate()}`.padStart(2, '0')
    return `${y}-${m}-${d}`
  },

  onReachBottom() {
    this.loadMessages(false)
  },

  onPullDownRefresh() {
    this.loadMessages(true)
  }
})